﻿using System;
using WJP.ComponentModel;
using WJP.WPF.Shell;

namespace WJP.WPF
{
    public class ClientApp : AppBase
    {
        public static ClientApp CurrentClientApp;
        private IClientAppRuntime _wpfApp;

        /// <summary>
        /// 注册客户端应用程序
        /// <para>一般在WPF Application 类的构造函数中调用此方法</para>
        /// </summary>
        /// <param name="wpfClientApp"></param>
        /// <returns></returns>
        public static ClientApp Register(IClientAppRuntime wpfClientApp)
        {
            if (wpfClientApp == null)
                throw new ArgumentNullException(nameof(wpfClientApp));
            ClientApp clientApp = new ClientApp();
            CurrentClientApp = clientApp;
            clientApp.AttachTo(wpfClientApp);
            return clientApp;
        }

        private void AttachTo(IClientAppRuntime wpfApp)
        {
            wpfApp.Startup += (s, e) => Startup();
            wpfApp.Exit += (s, e) => ExitApp();
            _wpfApp = wpfApp;
        }

        protected void Startup()
        {
            try
            {
                StartupApplication();
            }
            catch (Exception ex)
            {
                string message = ex.GetBaseException().Message;
                App.MessageBox.Show("程序启动时出现异常，程序即将退出……\r\n" + message + "\r\n" + ex.Message + "程序启动异常");
                Logger.Error("程序启动时出现异常");
                Shutdown();
            }
        }

        protected void ExitApp()
        {
            try
            {
                OnExit();
            }
            catch (Exception ex)
            {
                Logger.Error("系统退出异常", ex);
            }
        }

        protected override void InitEnvironment()
        {
            base.InitEnvironment();
            PlatformEnvironment.Location.DataPortalMode = DataPortalMode.CSClient;
        }

        public void Shutdown()
        {
            _wpfApp.Shutdown();
        }
    }
}
